package com.allen.retrofit2_rxjava2.view.selectImage.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;


/**
 * 类描述：FileUtil
 */
public class FileUtil {

    public static File updateDir = null;
    public static File updateFile = null;
    /***********
     * 保存升级APK的目录
     ***********/
    public static final String JsonBao = "jsonbao";

    public static boolean isCreateFileSucess;


    /**
     * 方法描述：createFile方法
     *
     * @return
     * @see FileUtil
     */
//    public static String path = getPath();
    public static void createFile(String app_name) {

//        if (Environment.MEDIA_MOUNTED.equals(Environment
//                .getExternalStorageState())) { //该方法为判断是否有外挂路径 但是有外挂无sd卡路径 无法创建
        if (!TextUtils.isEmpty(Environment.getExternalStorageDirectory()
                .getAbsolutePath())) {
            updateDir = new File(Environment.getExternalStorageDirectory()
                    + "/" + JsonBao + "/");
            isCreateFileSucess = true;
            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
            updateFile = new File(updateDir.getAbsolutePath(), app_name + ".apk");
            Log.i("updateDir", "" + updateDir);
            if (!updateFile.exists()) {
                try {
                    updateFile.createNewFile();
                } catch (IOException e) {
                    isCreateFileSucess = false;
                    e.printStackTrace();
                }
            }
        } else {
            Log.d("path", "地址为空");
            if (!TextUtils.isEmpty(Environment.getDataDirectory().toString())) {
                updateDir = new File(Environment.getDataDirectory()
                        + "/" + JsonBao + "/");//  获得根目录/data 内部存储路径 data路径读写失败 是不是权限问题？

                if (!updateDir.exists()) {
                    updateDir.mkdirs();
                }

                updateFile = new File(updateDir.getAbsolutePath(), app_name + ".apk");
                Log.i("updateFile", "" + updateDir + "/" + app_name + ".apk");
                Log.i("updateDir", "" + updateDir);
                if (!updateFile.exists()) {
                    try {
                        updateFile.createNewFile();
                    } catch (IOException e) {
                        isCreateFileSucess = false;
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static File getUpDatePath(String app_name) {
        if (!TextUtils.isEmpty(Environment.getExternalStorageDirectory()
                .getAbsolutePath())) {
            updateDir = new File(Environment.getExternalStorageDirectory()
                    + "/" + JsonBao + "/");
            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
            updateFile = new File(updateDir.getAbsolutePath(), app_name + ".apk");
        } else if (!TextUtils.isEmpty(Environment.getDataDirectory().toString())) {
            updateDir = new File(Environment.getDataDirectory()
                    + "/" + JsonBao + "/");//  获得根目录/data 内部存储路径 data路径读写失败 是不是权限问题？

            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
            updateFile = new File(updateDir.getAbsolutePath(), app_name + ".apk");
        }
        return updateFile;
    }

    public static String getUpDatePath() {
        if (!TextUtils.isEmpty(Environment.getExternalStorageDirectory()
                .getAbsolutePath())) {
            updateDir = new File(Environment.getExternalStorageDirectory()
                    + "/" + JsonBao);
            Log.d("updateDir", updateDir.getAbsolutePath());
            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
        } else if (!TextUtils.isEmpty(Environment.getDataDirectory().toString())) {
            updateDir = new File(Environment.getDataDirectory()
                    + "/" + JsonBao);//  获得根目录/data 内部存储路径 data路径读写失败 是不是权限问题？

            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
        }
        return updateDir.getAbsolutePath();
    }

    public static boolean inputStreamToOutputStream(InputStream input,
                                                    OutputStream output) {
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        in = new BufferedInputStream(input, 8 * 1024);
        out = new BufferedOutputStream(output, 8 * 1024);
        int b;
        try {
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static String inputStreamToString(InputStream in) {
        String result = "";
        if (null != in) {
            InputStreamReader ir = null;
            BufferedReader br = null;
            StringBuffer sb = new StringBuffer();
            try {
                ir = new InputStreamReader(in);
                br = new BufferedReader(ir);
                String line;
                while ((line = br.readLine()) != null)
                    sb.append("/n").append(line);
                if (result.length() > 0)
                    result = result.substring("/n".length());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ir != null)
                        ir.close();
                    if (br != null)
                        br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static InputStream byteToInputStream(byte[] bytes) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return bais;
    }
    //图片压缩 300k左右

    public static String getThumbUploadPath(String oldPath, int bitmapMaxWidth) throws Exception {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(oldPath, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int reqHeight = 0;
        int reqWidth = bitmapMaxWidth;
        reqHeight = (reqWidth * height) / width;
        // 在内存中创建bitmap对象，这个对象按照缩放大小创建的
        options.inSampleSize = calculateInSampleSize(options, bitmapMaxWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
        Bitmap bm = compressImage(Bitmap.createScaledBitmap(bitmap, bitmapMaxWidth, reqHeight, false));

        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        System.gc();

        return saveMyBitmap(bm);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    private static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            options -= 10;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

    }

    /**
     * 保存Bitmap到sd卡
     *
     * @param mBitmap
     * @return
     */
    private static String saveMyBitmap(Bitmap mBitmap) {
        if (!checkSDcardValid() || !createDir()) {
            return "";
        }
        String currentPhotoName = System.currentTimeMillis() + ".jpg";
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/zpay/");
        File out = new File(dir, currentPhotoName);

        try {
            out.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(out);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d("fileutil", "压缩图路径：" + out.getAbsolutePath());
        if (mBitmap != null && !mBitmap.isRecycled()) {
            mBitmap.recycle();
        }

        System.gc();
        return out.getAbsolutePath();
    }

    //检测sd卡是否可用
    public static boolean checkSDcardValid() {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            Log.e("fileutil", "sd卡不可用！");
            return false;
        }
        return true;
    }

    //判断文件夹是否创建成功
    public static boolean createDir() {
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/zpay/");
        Log.d("fileutil", "文件夹路径：" + dir.getAbsolutePath());
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                Log.e("fileutil", "创建文件夹失败！");
                return false;
            }
        }
        return true;
    }

    /*将图片按地址转成控件大小*/
    public static Bitmap createBitmap(String path, int w, int h) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            // 这里是整个方法的关键，inJustDecodeBounds设为true时将不为图片分配内存。
            BitmapFactory.decodeFile(path, opts);
            int srcWidth = opts.outWidth;// 获取图片的原始宽度
            int srcHeight = opts.outHeight;// 获取图片原始高度
            int destWidth = 0;
            int destHeight = 0;
            // 缩放的比例
            double ratio = 0.0;
            if (srcWidth < w || srcHeight < h) {
                ratio = 0.0;
                destWidth = srcWidth;
                destHeight = srcHeight;
            } else if (srcWidth > srcHeight) {// 按比例计算缩放后的图片大小，maxLength是长或宽允许的最大长度
                ratio = (double) srcWidth / w;
                destWidth = w;
                destHeight = (int) (srcHeight / ratio);
            } else {
                ratio = (double) srcHeight / h;
                destHeight = h;
                destWidth = (int) (srcWidth / ratio);
            }
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
            newOpts.inSampleSize = (int) ratio + 1;
            // inJustDecodeBounds设为false表示把图片读进内存中
            newOpts.inJustDecodeBounds = false;
            // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
            newOpts.outHeight = destHeight;
            newOpts.outWidth = destWidth;
            // 获取缩放后图片
            return BitmapFactory.decodeFile(path, newOpts);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     *  
     *  * 验证手机号格式正确性 
     *  
     */
    public static boolean isMobileNO(String mobiles) {
        /* 
    移动：134、135、136、137、138、139、150、151、147(TD)、157(TD)、158、159、178、187、188 
    联通：130、131、132、152、155、156、176、185、186 
    电信：133、153、177、180、189、199（1349卫通） 
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9 
    */
        String telRegex = "[1][23456789]\\d{9}";//"[1]"代表第1位为数字1，"[4578]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。  
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else {
            return mobiles.matches(telRegex);
        }
    }

    public static boolean isShenFenNO(String ShenFen) {

        String ShenFenRegex = "^(\\d{14}|\\d{17})(\\d|[xX])$";
        if (TextUtils.isEmpty(ShenFen)) {
            return false;
        } else {
            return ShenFen.matches(ShenFenRegex);
        }
    }

    @SuppressLint("SdCardPath")
    public static String getPath() {
        String sdcard_path = null;
        if (!TextUtils.isEmpty(Environment.getExternalStorageDirectory()
                .getAbsolutePath())) {
            sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
            return sdcard_path;
        } else if (!TextUtils.isEmpty(Environment.getDataDirectory().toString())) {
            sdcard_path = Environment.getDataDirectory().toString();
            return sdcard_path;

        } else {

            String sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
            if (sd_default.endsWith("/")) {
                sd_default = sd_default.substring(0, sd_default.length() - 1);
            }
            // 得到路径
            try {
                Runtime runtime = Runtime.getRuntime();
                Process proc = runtime.exec("mount");
                InputStream is = proc.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                String line;
                BufferedReader br = new BufferedReader(isr);
                while ((line = br.readLine()) != null) {
                    if (line.contains("secure"))
                        continue;
                    if (line.contains("asec"))
                        continue;
                    if (line.contains("fat") && line.contains("/mnt/")) {
                        String columns[] = line.split(" ");
                        if (columns != null && columns.length > 1) {
                            if (sd_default.trim().equals(columns[1].trim())) {
                                continue;
                            }
                            sdcard_path = columns[1];
                        }
                    } else if (line.contains("fuse") && line.contains("/mnt/")) {
                        String columns[] = line.split(" ");
                        if (columns != null && columns.length > 1) {
                            if (sd_default.trim().equals(columns[1].trim())) {
                                continue;
                            }
                            sdcard_path = columns[1];
                        }
                    }
                }
                Log.d("sdcard_path", sdcard_path);
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("获取sd卡路径异常", "SdCardPath");
            }
        }
        return sdcard_path;
    }

//    public static String getsmsyzm(Activity c) {  
//        Uri uri = Uri.parse("content://sms/inbox");
//        String[] projection = new String[]{"address", "person", "body"};
//        String selection = " address='" + "1069083125922" + "' ";
//        String[] selectionArgs = new String[]{
//        };
//        String sortOrder = "date desc";
//        @SuppressWarnings("deprecation")
//        Cursor cur = c.managedQuery(uri, projection, selection, selectionArgs, sortOrder);
//        if (cur != null && cur.getCount() > 0) {
//            cur.moveToFirst();
//            String body = cur.getString(cur.getColumnIndex("body")).replaceAll(
//                    "\n", " ");
//            cur.close();
//            return getyzm(body, 4);
//        }
//        cur.close();
//        return null;
//    }
//
//    /**
//     *  从短信字符窜提取验证码
//     *  @param body 短信内容
//     *  @param YZMLENGTH  验证码的长度 一般6位或者4位
//     *  @return 接取出来的验证
//     */
//    public static String getyzm(String body, int YZMLENGTH) {
//        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组
//        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数
//        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
//        Pattern p = Pattern.compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");
//        Matcher m = p.matcher(body);
//        if (m.find()) {
//            System.out.println(m.group());
//            return m.group(0);
//        }
//        return null;
//    }

    /**
     *  
     *  判定输入汉字 
     *  @param c 
     *  @return 
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static InputFilter filer() {
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (!isChinese(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }
        };
        return filter;
    }


    /**
     * 验证输入身份证号
     *
     * @param
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsIDcard(String str) {
        String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        return match(regex, str);
    }

    /**
     * 验证输入车牌号
     *
     * @param
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsCarNo(String str) {
        if (7 == str.length()) {
            String regex = "^[冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1}$";
            if (match(regex, str)) {
                str = str.substring(2);
                Log.d(str, str);
                int d = 0;
                for (int i = 0; i < str.length(); i++) {
                    char c = str.charAt(i);
                    if (c >= 'A' && c <= 'Z') {
                        d++;
                    }
                }
                if (d > 2) {
                    return false;
                } else {
                    return true;
                }
            }
            return false;
        } else if (8 == str.length()) {
            String regex = "[\u4e00-\u9fa5][a-zA-Z](([DF][a-zA-Z0-9]{5})|([a-zA-Z0-9]{5}[DF]))";
            if (match(regex, str)) {
                str = str.substring(2);
                int d = 0;
                for (int i = 0; i < str.length(); i++) {
                    char c = str.charAt(i);
                    if (c >= 'A' && c <= 'Z') {
                        d++;
                    }
                }
                if (d > 3) {
                    return false;
                } else {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * 验证密码强度
     */

    public static int password(String str) {
        String pass1 = "0123456789";
        String pass2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLIMNOPQRSTUVWXYZ";
        String pass3 = ",.~!@#%";
        int p1 = 0;
        int p2 = 0;
        int p3 = 0;
        if (str.length() >= 6) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (pass1.contains(String.valueOf(c))) {
                    p1 = 1;
                }
                if (pass2.contains(String.valueOf(c))) {
                    p2 = 1;
                }
                if (pass3.contains(String.valueOf(c))) {
                    p3 = 1;
                }
            }
        }

        return p1 + p2 + p3;
    }

    /**
     * @param regex 正则表达式字符串
     * @param str   要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }


//    public static boolean equalList(List<Banners> list1, List<Banners> list2) {
//        if (list1.size() != list2.size()) {
//            Log.d("equalList", "false");
//            return false;
//        }
//        for (int i = 0; i < list1.size(); i++) {
//            if (!list1.get(i).getImageAddress().equals(list2.get(i).getImageAddress())) {
//                Log.d("equalList", "false");
//                return false;
//            }
//        }
//        Log.d("equalList", "true");
//        return true;
//    }


    //删除文件夹和文件夹里面的文件
    public static void deleteDir(String pPath) {
        File dir = new File(pPath);
        Log.d("删除文件", dir.getAbsolutePath());
        try {
            dir.delete();
            Log.d("删除文件", "删除成功");
        } catch (Exception e) {

        }
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        }
        dir.delete();
//        for (File file : dir.listFiles()) {
//            if (file.isFile()) {
//                Log.d("删除文件", file.getAbsolutePath());
//                file.delete(); // 删除所有文件
//            } else if (file.isDirectory()) {
//                Log.d("删除路径", file.getAbsolutePath());
//                deleteDirWihtFile(file); // 递规的方式删除文件夹
//            }
//        }
        Log.d("删除文件", "删除成功");
        dir.delete();// 删除目录本身
    }

    public static List<Integer> addInt(List<Integer> ibeacons, int num) {
        ibeacons.add(num);
        Log.d("ide", ibeacons.toString());
        return get3(ibeacons);
    }


    //移除大于3的元素
    private static List<Integer> get3(List<Integer> ibeacons) {

        if (ibeacons.size() > 3) {
            ibeacons.remove(0);
            get3(ibeacons);
        }
        Log.d("idem", ibeacons.toString());
        return ibeacons;
    }

    /**
     * 文件转Base64.
     * @param filePath
     * @return
     */
    public static String file2Base64(String filePath) {
        FileInputStream objFileIS = null;
        try {
            objFileIS = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
        byte[] byteBufferString = new byte[1024];
        try {
            for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1; ) {
                objByteArrayOS.write(byteBufferString, 0, readNum);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);
        return videodata;
    }
}
